//
//  CacheSession.swift
//  NetworkKit
//
//  Created by TSYH on 2024/3/15.
//

import Foundation

public class CacheSession {
    private lazy var queue = DispatchQueue(label: "queue.request.cache")
    private lazy var semaphore = DispatchSemaphore(value: 1)
}

public extension CacheSession {
    func requestFileData(with fileName: String,
                                 completion: ((Data?) -> Void)?) {
        queue.async {
            if let path = Bundle.main.path(forResource: fileName, ofType: "json") {
                let url = URL(fileURLWithPath: path)
                do {
                    let data = try Data(contentsOf: url)
                    completion?(data)
                } catch let error {
                    completion?(nil)
                }
            } else {
                completion?(nil)
            }
        }
    }
}

// 缓存处理
extension CacheSession {
    // 缓存请求结果
    func saveCacheIfNeed(responseData: Data?,
                         for request: BaseRequest) {
        guard request.shouldCacheResponse,
              let data = responseData else {
            return
        }
        queue.async { [weak self] in
            self?.semaphore.wait()
            FileManager.default.write(data: data,
                                      to: request.dataCacheKey)
            self?.semaphore.signal()
        }
    }
    
    // 读取接口缓存
    func fetchCache(for request: BaseRequest,
                    completionHandler: ((Data?) -> Void)?) {
        guard request.shouldReadCache else {
            return
        }
        queue.async { [weak self] in
            self?.semaphore.wait()
            let data = FileManager.default.fileData(with: request.dataCacheKey)
            completionHandler?(data)
            self?.semaphore.signal()
        }
    }
}
